﻿using System.Reflection;
using Microsoft.Office.Server.Search.Query;

namespace Hvam.SharePoint.Search.Query
{
    public static class LocationExtensions
    {
        public static SortCollection GetSortList(this Location location)
        {
            var propertyInfo = location.GetType().GetProperty("LocationRuntime", BindingFlags.Instance | BindingFlags.NonPublic);
            var runtime = propertyInfo.GetGetMethod(true).Invoke(location, null);
            var runtimeType = runtime.GetType();

            // runtime.KeywordQueryObject.SortList
            var keywordQueryObjectPropertyInfo = runtimeType.GetProperty("KeywordQueryObject", typeof (KeywordQuery));
            if (keywordQueryObjectPropertyInfo != null)
            {
                var keywordQueryObjectGetMethod = keywordQueryObjectPropertyInfo.GetGetMethod();
                var keywordQueryObject = keywordQueryObjectGetMethod.Invoke(runtime, null);

                return GetSortListProperty(keywordQueryObject);
            }

            // runtime.SortList
            return GetSortListProperty(runtime);
        }

        private static SortCollection GetSortListProperty(object @object)
        {
            var sortListPropertyInfo = @object.GetType().GetProperty("SortList", typeof(SortCollection));
            if (sortListPropertyInfo != null)
            {
                var getMethod = sortListPropertyInfo.GetGetMethod();

                return (SortCollection) getMethod.Invoke(@object, null);
            }

            return null;
        }
    }
}
